import axios from "axios";
import { Notification, MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken, removeToken } from "@/utils/auth";
import router, { resetRouter } from "@/router";

import { getHeadersToken } from "@/utils/index";
import { resetTime } from "./serverTime";
import serverTimeInterceptor from "./interceptor/serverTimeInterceptor";
import repetitiveInterceptor from "./interceptor/repetitiveInterceptor";

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 30 * 1000,
});

let _cacheToken = ''

// request拦截器
service.interceptors.request.use(
  (config) => {
    if (!config.noToken) {
      const token = getToken()
      if (_cacheToken && token && _cacheToken != token) {
        MessageBox.confirm("有新账号登录，确定后刷新页面！", "系统提示", {
          showCancelButton: false,
          type: "warning",
        }).finally(() => {
          location.reload()
        })
      }
      _cacheToken = token
      config.headers["token"] = getHeadersToken(token, config.serverTime); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 请求拦截器后绑定的先执行
serverTimeInterceptor(service.interceptors)
// repetitiveInterceptor(service.interceptors)

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    // console.log("响应拦截器===", res);
    // 直接返回结果
    if (res.config.directReturnData) {
      return res;
    }
    if (!res.data.content) {
      return res.data;
    }

    const code = res.data.content.code;
    if (code === 7) {
      resetTime()
      
      // token无效
      const fullPath = router.history.current.fullPath;
      return MessageBox.confirm("登录状态已过期，您可以继续留在该页面，或者重新登录", "系统提示", {
        confirmButtonText: "重新登录",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        store.dispatch("logout").then(() => {
          Message.success("退出成功！");
          router.push(`/login?redirect=${fullPath}`);
        });
        return Promise.reject()
      })
    } else {
      return res.data;
    }
  },
  (error) => {
    if (axios.isCancel(error)) {
      Message({ message: '操作过于频繁！', type: "error", duration: 5 * 1000, });
      return Promise.reject(error)
    }
    if (!(error && error.config && error.config.errorHandle)) {
      Message({
        message: error.message,
        type: "error",
        duration: 5 * 1000,
      });
    }

    return Promise.reject(error);
  }
);

export default service